package com.lp.yuojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.lp.yuojbackendcommon.common.ErrorCode;
import com.lp.yuojbackendcommon.exception.BusinessException;
import com.lp.yuojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.lp.yuojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.lp.yuojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.lp.yuojbackendjudgeservice.judge.strategy.JudgeContext;
import com.lp.yuojbackendmodel.codesrandbox.ExecutedCodeRequest;
import com.lp.yuojbackendmodel.codesrandbox.ExecutedCodeResponse;
import com.lp.yuojbackendmodel.codesrandbox.JudgeInfo;
import com.lp.yuojbackendmodel.dto.question.JudgeCase;
import com.lp.yuojbackendmodel.entity.Question;
import com.lp.yuojbackendmodel.entity.QuestionSubmit;
import com.lp.yuojbackendmodel.enums.QuestionSubmitStatusEnum;
import com.lp.yuojbackendserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionFeignClient questionFeignClient;
    @Value("${codesandbox.type:example}")
    private String type;
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1.获取提交的问题
        QuestionSubmit questionSubmit = questionFeignClient.getSubmitById(questionSubmitId);
        if (questionSubmit==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getById(questionId);
        if (question==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        // 2.如果提交题目的状态为等待中，则不执行沙箱
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }
        // 3.设置提交题目的状态为判题中
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean result = questionFeignClient.updateSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        }
        // 4.调用沙箱执行代码
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        // 获取用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecutedCodeRequest executedCodeRequest = ExecutedCodeRequest.builder()
                .inputList(inputList)
                .code(code)
                .language(language)
                .build();
        ExecutedCodeResponse executedCodeResponse = codeSandbox.executeCode(executedCodeRequest);
        // 获取执行结果
        List<String> outputList = executedCodeResponse.getOutputList();
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executedCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        // 调用判题管理
        JudgeManager judgeManager = new JudgeManager();
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 更新数据库信息
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        result = questionFeignClient.updateSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        }
        // 从数据库中查询更新后的信息
        return questionFeignClient.getSubmitById(questionId);
    }
}
